<template>
  <div class="mobileDataManagement">
    <MetaSearchForm @on-search="tableSearch">
      <el-form ref="mobileDataManagement_form" :model="searchData" label-width="80px">
        <el-form-item label="设备" class="mobileDataManagement_searchFromItem">
          <el-select v-model="searchData.equipmentid" filterable clearable placeholder="请选择设备">
            <el-option
              v-for="item in equipmentList"
              :key="item.id"
              :label="item.equipmentname"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集时间" class="mobileDataManagement_searchFromItem">
          <el-date-picker
            v-model="searchData.dateBetween"
            type="datetimerange"
            range-separator="-"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="mobileDataManagementTable"
      :autoReqFirst="false"
      class="mobileDataManagement_table"
      table-title="数据管理"
      :needCheckbox="true"
      :need-checkbox="false"
      :is-auto-req="true"
      :req-url="reqUrl"
      :req-data="searchDataForTable"
      req-method="post"
      :display-item="displayItem"
      :btn-group="btnGroup"
      @btnClick="tableBtnClick"
      :line-btn-group="lineBtnGroup"
      @lineBtnClick="tableLineBtnClick"
    />
    <el-dialog
      v-if="echartDialog"
      title="查看光谱曲线"
      :visible.sync="echartDialog"
      width="60%"
      center
      modal
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="echartForReflectivityBg">
        <div id="echartForReflectivity" class="echartForReflectivity"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MetaPageTable from "../components/MetaPageTable";
import MetaSearchForm from "../components/MetaSearchForm";
import deepClone from "../utils/deepClone";
import utils from "../utils/utils";
export default {
  name: "mobileDataManagement",
  components: {
    MetaPageTable,
    MetaSearchForm,
  },
  data() {
    return {
      echartDialog: false,
      searchData: {
        equipmentid: "",
        dateBetween: [],
      },
      searchDataForTable: {},
      reqUrl: process.env.PROGOO_GATE_WATER + "admin/appCollection/details",
      displayItem: [
        {
          label: "采集时间",
          prop: "collectTime",
        },
        {
          label: "采集位置（经度）",
          prop: "longitude",
        },
        {
          label: "采集位置（纬度）",
          prop: "latitude",
        },
        {
          label: "采集用户",
          prop: "userId",
        },
        {
          label: "上传时间",
          prop: "transmissiontime",
        },
      ],
      btnGroup: [
        {
          id: "exportRawData",
          title: "导出原始数据",
        },
      ],
      lineBtnGroup: [
        {
          id: "chart",
          title: "查看光谱",
        },
      ],
      itemExportData: {
        dateBetween: [],
      },
      rolesList: [],
      companyList: [],
      equipmentList: [],
      paramsList: [],
      echartForReflectivity: null,
      exportDBRules: {
        eid: [{ required: true, message: "请选择设备", trigger: "change" }],
      },
    };
  },
  created() {
    window.onresize = () => {
      if (this.echartForReflectivity) {
        this.echartForReflectivity.resize();
      }
    };
  },
  mounted() {
    this.getEquipmentList(() => {
      if (this.equipmentList.length > 0) {
        this.searchData.equipmentid = this.equipmentList[0].id;
        this.searchData.dateBetween = [];
        let nowDay = utils.formatDate("yyyy-MM-dd", new Date());
        let startDay = utils.formatDate("yyyy-MM-dd", this.getBeforeDate(7));
        this.searchData.dateBetween.push(startDay + " 00:00:00");
        this.searchData.dateBetween.push(nowDay + " 23:59:59");
        this.tableSearch();
      }
    });
  },
  methods: {
    getEquipmentList(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/equipment/user",
        method: "post",
        data: {
          equipmentType: [2],
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.equipmentList = res.data.result;
          callback();
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    tableLineBtnClick(item) {
      if (item.button === "chart") {
        this.echartDialog = true;
        this.$nextTick(() => {
          this.initEchart(item.rows);
        });
      }
    },
    initEchart(itemDatas) {
      let echarts = require("echarts");
      let chartDoc = document.getElementById("echartForReflectivity");
      this.echartForReflectivity = echarts.init(chartDoc);
      this.echartForReflectivity.setOption({
        title: {
          text: "反射率",
          x: "center",
          y: "top",
        },
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "5%",
          bottom: "5%",
          top: "10%",
          height: "80%",
          right: "2%",
          show: true,
          // containLabel: true
        },
        xAxis: {
          type: "category",
          axisLabel: {
            show: true,
            fontSize: 10,
          },
          boundaryGap: false,
          // data: data.xData
        },
        yAxis: {
          type: "value",
          axisLabel: {
            show: true,
            fontSize: 10,
          },
          scale: true,
        },
        series: [
          {
            name: "反射率",
            type: "line",
            stack: "反射率",
            smooth: true,
            data: itemDatas.reflectivity,
          },
        ],
      });
      this.$nextTick(() => {
        this.echartForReflectivity.resize();
      });
    },
    tableBtnClick(item) {
      if (item.button === "exportRawData") {
        if (this.equipmentList.length <= 0) {
          return;
        }
        let params = {};
        params.datestart = this.searchDataForTable.datestart
          ? this.searchDataForTable.datestart
          : "";
        params.dateend = this.searchDataForTable.dateend
          ? this.searchDataForTable.dateend
          : "";
        params.equipmentid = this.searchDataForTable.equipmentid
          ? this.searchDataForTable.equipmentid
          : "";
        // let eName = ''
        // for(let i in this.equipmentList) {
        //   if(this.searchDataForTable.equipmentid === this.equipmentList[i].id) {
        //     eName = this.equipmentList[i].equipment_name
        //     let start = utils.getStrByUnderlineBefore(this.searchDataForTable.datestart, ' ')
        //     let end = utils.getStrByUnderlineBefore(this.searchDataForTable.dateend, ' ')
        //     if(this.searchDataForTable.datestart && this.searchDataForTable.dateend) {
        //       if(start == end) {
        //         eName += "(" + start + ")"
        //       }else {
        //         eName += "(" + start + " - " + end + ")"
        //       }
        //     }
        //     break
        //   }
        // }
        let token = localStorage.getItem("token");
        this.axios({
          method: "post",
          url: process.env.PROGOO_GATE_WATER + "admin/appCollection/export",
          data: params,
          // token
          headers: {
            "x-auth-token": token,
          },
          responseType: "blob",
        }).then((res) => {
          if ((res.code && res.code == 400) || (res.data.code && res.data.code == 400)) {
            this.$notify.error({
              title: "错误",
              message: res.data.message,
            });
            return;
          }
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "便携式光谱数据.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        });
      }
    },
    doExportData(resData) {
      let equip = {};
      let wave = {};
      for (let i in this.equipmentList) {
        equip[this.equipmentList[i].id] = this.equipmentList[i].equipmentname;
        wave[this.equipmentList[i].id] = this.equipmentList[i].wavelength;
      }
      let enumType = {
        adl: "暗电流",
        bzb: "标准版",
        dc: "单次采集",
        lx: "连续采集",
        ds: "定时采集",
      };
      let header = [
        "设备名称",
        "dn值",
        "反射率",
        "指令",
        "经度",
        "纬度",
        "采集类型",
        "采集时间",
        "备注",
      ];
      let exData = [];
      for (let i in resData) {
        let itemList = [];
        itemList.push(equip[resData[i].equipmentid]);
        itemList.push(resData[i].dndata);
        itemList.push(resData[i].reflectivity);
        itemList.push(resData[i].dnvalue);
        itemList.push(resData[i].longitude);
        itemList.push(resData[i].latitude);
        itemList.push(enumType[resData[i].type]);
        itemList.push(resData[i].collectTime);
        itemList.push(resData[i].remark);
        exData.push(itemList);
      }
      if (resData.length > 0) {
        let waveList = [];
        waveList.push("中心波长");
        waveList.push(wave[resData[0].equipmentid]);
        exData.push(waveList);
      }

      let title = "原始数据";
      this.$export_json_to_excel(header, exData, title);
    },
    tableSearch() {
      let param = {};
      for (let key in this.searchData) {
        if (key === "dateBetween") {
          param.datestart =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][0]
              : "";
          param.dateend =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][1]
              : "";
        } else {
          param[key] = this.searchData[key];
        }
      }
      this.searchDataForTable = param;
      this.$nextTick(() => {
        this.$refs.mobileDataManagementTable.formDataInit(true);
      });
    },
    getBeforeDate(n) {
      const d = new Date();
      let mon = d.getMonth() + 1;
      const day = d.getDate();
      if (day <= n) {
        if (mon > 1) {
          mon = mon - 1;
        } else {
          mon = 12;
        }
      }
      d.setDate(d.getDate() - n);
      return d;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.mobileDataManagement {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .mobileDataManagement_table {
    width: 100%;
    overflow-y: unset;
  }
  .echartForReflectivityBg {
    width: 100%;
    height: 400px;
    box-sizing: border-box;
    padding: 10px 20px;
    .echartForReflectivity {
      width: 100%;
      height: 100%;
    }
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
  .roleChooseSelect {
    width: 100%;
  }
  .mobileDataManagement_searchFromItem {
    float: left;
  }
}
</style>
